package com.daling.product_processor.util;


import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.*;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

public class OssUtil {
    private static final String ENDPOINT = "https://oss-cn-shanghai.aliyuncs.com";
    private static final String KEY = "LTAI5tKYTjzbdRE91rc7URgN";
    private static final String SECRET = "3YaMG1aM0jjJK1TFTL0SqNtDSmgdCv";
    private static final String BUCKET = "crawl-v3";

    private static final Object lock = new Object();
    private static final String regexPattern = "^raw/[0-9]*-[\u4e00-\u9fa5]*-[\u4e00-\u9fa5]*-[0-9a-zA-Z]*-[0-9]{10}\\.(csv|json)$";

    public static String getOneCSVFile() {
        synchronized (lock) {
            OSS oss = getOSS();
            try {
                ObjectListing objectListing = oss.listObjects(
                        new ListObjectsRequest(BUCKET)
                                .withMaxKeys(10)
                                .withMarker("raw/")
                );
                objectListing.getCommonPrefixes();
                List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
                for (OSSObjectSummary summary : sums) {
                    String filename = summary.getKey();
                    if (filename.matches(regexPattern)) {
                        return filename;
                    }
                    delFile(filename);
                }
                return null;
            } finally {
                oss.shutdown();
            }
        }
    }

    public static String[] splitFilename(String filename) {
        String[] ret = new String[3];
        if (filename.matches(regexPattern)) {
            String sub = filename.substring(filename.indexOf("/") + 1);
            ret[0] = sub;
            String[] split = sub.split("\\.");
            ret[1] = split[0];
            ret[2] = split[1];
            return ret;
        }
        return null;
    }

    public static void delFile(String filename) {
        if (filename == null || filename.matches(regexPattern)) {
            return;
        }
        synchronized (lock) {
            OSS oss = getOSS();
            try {
                oss.deleteObject(BUCKET, filename);
            } finally {
                oss.shutdown();
            }
        }
    }

    public static OssBufferedReader getFileReader(String filename) {
        if (filename == null || filename.isEmpty() || !filename.matches(regexPattern)) {
            return null;
        }
        synchronized (lock) {
            OSS oss = getOSS();
            OSSObject ossObject = oss.getObject(BUCKET, filename);
            return new OssBufferedReader(
                    oss,
                    new BufferedReader(
                            new InputStreamReader(
                                    ossObject.getObjectContent()
                            )
                    )
            );
        }
    }

    public boolean readLine(String filename, LineRead lineRead) throws Throwable {
        if (filename == null || filename.isEmpty() || !filename.matches(regexPattern)) {
            return false;
        }
        OSS oss = getOSS();
        try {
            OSSObject ossObject = oss.getObject(BUCKET, filename);
            BufferedReader br = new BufferedReader(
                    new InputStreamReader(
                            ossObject.getObjectContent()
                    )
            );

            while (true) {
                String line;
                try {
                    line = br.readLine();
                } catch (IOException e) {
                    continue;
                }
                if (line == null) break;

                lineRead.apply(line);
            }
        } finally {
            oss.shutdown();
        }
        return true;
    }

    public void putFile(File file) {
        OSS oss = getOSS();
        try {
            System.out.println(file.getName());
            PutObjectRequest putObjectRequest = new PutObjectRequest(
                    BUCKET,
                    "raw/" + file.getName(),
                    file
            );
            oss.putObject(putObjectRequest);
        } finally {
            oss.shutdown();
        }
    }

    private static OSS getOSS() {
        return new OSSClientBuilder().build(ENDPOINT, KEY, SECRET);
    }

    public interface LineRead {
        void apply(String line);
    }

    public static class OssBufferedReader implements AutoCloseable {
        private final BufferedReader br;
        private final OSS oss;

        public OssBufferedReader(OSS oss, BufferedReader br) {
            this.oss = oss;
            this.br = br;
        }

        public String readLine() throws IOException {
            return br.readLine();
        }

        public void close() throws IOException {
            if (br != null) {
                br.close();
            }
            if (oss != null) {
                oss.shutdown();
            }
        }
    }
}

